package part12cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @description: ABA问题与解决
 * @author: zhang hang
 * @date: 2024/3/24 17:34.
 * @version: 1.0
 */
public class CASTest03 {

    static AtomicReference<Integer> atomicReference = new AtomicReference<>(100);

    // 演示ABA问题
    public static void main01(String[] args) {
        new Thread(() -> {
            atomicReference.compareAndSet(100, 101);
            atomicReference.compareAndSet(101, 100);
        }, "T1").start();

        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(atomicReference.compareAndSet(100, 2020) + "=>" + atomicReference.get());
        }, "T2").start();
    }


    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

    // 解决ABA问题
    public static void main(String[] args) {
        new Thread(() -> {
            // 获得版本号
            System.out.println("T1 stamp 01=>" + atomicStampedReference.getStamp());

            // 暂停2秒钟，保证下面线程获得初始版本号
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            atomicStampedReference.compareAndSet(100, 101, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);

            System.out.println("T1 stamp 02=>" + atomicStampedReference.getStamp());

            atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
        }, "T1").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp(); // 获得版本号 System.out.println("T2 stamp 01=>"+stamp);
            // 暂停3秒钟，保证上面线程先执行
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean result = atomicStampedReference.compareAndSet(100, 2019, stamp, stamp + 1);
            System.out.println("T2 是否修改成功 =>" + result);
            System.out.println("T2 最新stamp =>" + atomicStampedReference.getStamp());
            System.out.println("T2 当前的最新值 =>" + atomicStampedReference.getReference());
        }, "T2").start();
    }
}
